<script setup>
import { useMarked } from '@/hooks/useMarked';
import { usePreferredDark, useClipboard } from '@vueuse/core';
import { toLower } from 'lodash';

const props = defineProps({
  content: {
    type: String,
    default: '',
  },
});
const { content, isMarkdown, anchors, isDark } = useMarked(
    props.content,
    'demo.md'
);
const isPreferredDark = usePreferredDark();

const copyedList = [];

isDark.value = document.documentElement.classList.contains('dark');
watch(isDark, (v) => {
  document.documentElement.classList[v ? 'add' : 'remove']('dark');
});

const handleClick = () => (isDark.value = !isDark.value);

// 事件代理
const handleEventDelegationClick = (e) => {
  e.preventDefault();

  const el = e.target;
  const elName = toLower(el.nodeName);
  const elClass = el.classList;
  const elType = el.dataset.type;
  const elParent = el.parentNode;
  const elParentName = toLower(elParent.nodeName);

  // 复制粘贴
  if (elName === 'button' && elType === 'copy') {
    const source = el.nextElementSibling.textContent;
    const { text, copy, copied } = useClipboard();
    // 判断冷却是否结束
    const index = copyedList.findIndex((item) => item === el);
    if (index > -1) return;

    /**
     * stackblitz 嵌套了 iframe，而 iframe 限制了复制粘贴功能
     *
     * 所以，以下代码无法在当前编辑器正常运行
     * 但是，代码是正确的
     */

    // 调用复制函数
    copy(source);

    watch(copied, (val) => {
      if (val) {
        el.textContent = 'copied!';
        console.log(el);
        // 记录已复制状态
        copyedList.push(el);
        // $message.success('复制代码成功')
      } else {
        el.textContent = 'copy';
        // 重置状态
        copyedList.splice(index, 1);
      }
    });
  }

  // // 链接拦截
  // if (elParentName === 'a' || elName === 'a') {
  //   const url = (elParentName === 'a' ? elParent : el).getAttribute('href');
  //   emit('link-before', url);
  // }

  // // 锚点
  // if (elName === 'span' && elType === 'anchor' && unref(anchorRef)) {
  //   // 调用子组件方法
  //   unref(anchorRef).scrollTo(el.dataset.hash);
  // }
};
</script>

<template>
  <div class="wrap">
    <button
        :class="['theme-btn', { btn_dark: isPreferredDark }]"
        @click="handleClick"
    >
      {{ isDark ? '光' : '暗' }}
    </button>
    <div
        :class="['markdown-body', { 'is-dark': isDark }]"
        v-html="content"
        @click="handleEventDelegationClick"
    ></div>
  </div>
</template>

<style lang="scss" scoped>
@import "./markdown";

.wrap {
  .markdown-body {
  @apply text-left;
  }

  .theme-btn {
  @apply bg-dark-50 text-light-50;
    &.btn_dark {
    @apply bg-light-50 text-dark-50;
    }
  }
}
</style>
